package com.niit.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.niit.common.Result;
import com.niit.model.Book;
import com.niit.service.BookService;
import com.niit.service.impl.BookServiceImpl;

/**
 * Servlet implementation class DeleteBookServlet
 */
@WebServlet("/DeleteBookServlet.do")
public class DeleteBookServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DeleteBookServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		Result result = null;

		String id = request.getParameter("id");
		System.out.println("删除id=" + id);
		// 判断编号是否已经存在，如果已经不存在，不允许删除
		BookService bookService = new BookServiceImpl();
		Book hasBook = bookService.getBookById(Integer.valueOf(id));
		if (hasBook != null) {
			bookService.deleteBookById(Integer.valueOf(id));
			result = Result.success("删除成功");
		} else {
			// 没有该书籍，不能删除
			System.out.println("删除失败，系统没有该书籍。");
			result = Result.error("删除失败，系统没有该书籍。");
		}
		// 返回JSON数据给前端
		JSONObject json = (JSONObject) JSONObject.toJSON(result);
		writer.print(json);
		writer.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
